<template>
	<view class="ship-cart-container">
		<!-- 自定义导航栏 -->
		<ob-navbar 
			title="船舶购物车"
			:show-back="true"
			:background="'#FFFFFF'"
		/>
		
		<!-- 船舶信息栏 -->
		<view class="ship-info-bar">
			<view class="ship-selector" @click="showShipModal = true">
				<view class="ship-details">
					<text class="ship-name">{{ currentShip.name || '请选择船舶' }}</text>
					<text v-if="currentShip.imo" class="ship-imo">IMO: {{ currentShip.imo }}</text>
				</view>
				<text class="selector-arrow">></text>
			</view>
			
			<view v-if="currentShip.id" class="ship-stats">
				<view class="stat-item">
					<text class="stat-label">预计到港:</text>
					<text class="stat-value">{{ currentShip.arrivalDate || '未设置' }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">目的港:</text>
					<text class="stat-value">{{ currentShip.destinationPort || '未设置' }}</text>
				</view>
			</view>
		</view>
		
		<!-- 购物车商品列表 -->
		<view v-if="cartItems.length > 0" class="cart-content">
			<view class="cart-header">
				<view class="select-all" @click="toggleSelectAll">
					<text class="checkbox" :class="{ checked: isAllSelected }">{{ isAllSelected ? '☑' : '☐' }}</text>
					<text class="select-text">全选</text>
				</view>
				<text class="total-count">共{{ cartItems.length }}件商品</text>
			</view>
			
			<view class="cart-list">
				<view 
					v-for="(item, index) in cartItems" 
					:key="item.id"
					class="cart-item"
				>
					<view class="item-checkbox" @click="toggleItemSelect(item.id)">
						<text class="checkbox" :class="{ checked: item.selected }">{{ item.selected ? '☑' : '☐' }}</text>
					</view>
					
					<image class="item-image" :src="item.image" mode="aspectFill" />
					
					<view class="item-info">
						<text class="item-name">{{ item.name }}</text>
						<view class="item-specs">
							<text class="spec-text">{{ formatSpecs(item.specs) }}</text>
						</view>
						<view class="item-meta">
							<text class="item-price">¥{{ item.price }}</text>
							<view class="quantity-controls">
								<text class="quantity-btn minus" @click="decreaseQuantity(item.id)">-</text>
								<text class="quantity-value">{{ item.quantity }}</text>
								<text class="quantity-btn plus" @click="increaseQuantity(item.id)">+</text>
							</view>
						</view>
					</view>
					
					<view class="item-actions">
						<text class="action-btn" @click="removeItem(item.id)">删除</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view v-else class="empty-cart">
			<ob-empty 
				:image="'/static/images/empty-cart.png'"
				title="船舶购物车为空"
				description="为您的船舶添加所需商品吧"
			/>
			<button class="browse-btn" @click="goToBrowse">
				<text class="browse-text">去逛逛</text>
			</button>
		</view>
		
		<!-- 推荐商品 -->
		<view v-if="recommendProducts.length > 0" class="recommend-section">
			<view class="section-header">
				<text class="section-title">为您推荐</text>
			</view>
			<scroll-view class="recommend-list" scroll-x="true">
				<view 
					v-for="product in recommendProducts" 
					:key="product.id"
					class="recommend-item"
					@click="goToProductDetail(product.id)"
				>
					<image class="recommend-image" :src="product.image" mode="aspectFill" />
					<text class="recommend-name">{{ product.name }}</text>
					<text class="recommend-price">¥{{ product.price }}</text>
				</view>
			</scroll-view>
		</view>
		
		<!-- 底部操作栏 -->
		<view v-if="cartItems.length > 0" class="bottom-bar">
			<view class="bar-left">
				<view class="total-info">
					<text class="total-label">合计:</text>
					<text class="total-price">¥{{ totalPrice }}</text>
				</view>
				<text class="save-info">已为船舶节省 ¥{{ savedAmount }}</text>
			</view>
			<button 
				class="checkout-btn"
				:class="{ disabled: selectedCount === 0 }"
				@click="goToCheckout"
			>
				<text class="checkout-text">结算({{ selectedCount }})</text>
			</button>
		</view>
		
		<!-- 船舶选择弹窗 -->
		<view v-if="showShipModal" class="ship-modal" @click="showShipModal = false">
			<view class="ship-modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">选择船舶</text>
					<text class="modal-close" @click="showShipModal = false">✕</text>
				</view>
				
				<view class="ship-list">
					<view 
						v-for="ship in shipList" 
						:key="ship.id"
						class="ship-option"
						:class="{ active: currentShip.id === ship.id }"
						@click="selectShip(ship)"
					>
						<view class="ship-info">
							<text class="ship-name">{{ ship.name }}</text>
							<text class="ship-imo">IMO: {{ ship.imo }}</text>
							<text class="ship-port">目的港: {{ ship.destinationPort }}</text>
						</view>
						<text v-if="currentShip.id === ship.id" class="ship-check">✓</text>
					</view>
				</view>
				
				<view class="modal-footer">
					<button class="add-ship-btn" @click="addNewShip">
						<text class="add-ship-text">+ 添加新船舶</text>
					</button>
				</view>
			</view>
		</view>
		
		<ob-loading :visible="isLoading" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue'
import cartApi from '../../api/cart.js'
import productApi from '../../api/product.js'
import shipApi from '../../api/ship.js'

const store = inject('$store')

// 响应式数据
const cartItems = ref([])
const currentShip = ref({})
const shipList = ref([])
const recommendProducts = ref([])
const isLoading = ref(false)
const showShipModal = ref(false)

// 计算属性
const isAllSelected = computed(() => {
	return cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
})

const selectedCount = computed(() => {
	return cartItems.value.filter(item => item.selected).length
})

const totalPrice = computed(() => {
	return cartItems.value
		.filter(item => item.selected)
		.reduce((total, item) => total + (item.price * item.quantity), 0)
		.toFixed(2)
})

const savedAmount = computed(() => {
	return cartItems.value
		.filter(item => item.selected)
		.reduce((total, item) => total + ((item.originalPrice - item.price) * item.quantity), 0)
		.toFixed(2)
})

// 页面生命周期
onMounted(() => {
	loadCartData()
	loadShipList()
	loadRecommendProducts()
})

// 加载购物车数据
const loadCartData = async () => {
	try {
		isLoading.value = true
		const response = await cartApi.getShipCart()
		cartItems.value = response.items || []
		currentShip.value = response.ship || {}
	} catch (error) {
		console.error('加载购物车失败:', error)
	} finally {
		isLoading.value = false
	}
}

// 加载船舶列表
const loadShipList = async () => {
	try {
		const response = await shipApi.getShipList()
		shipList.value = response.list || []
	} catch (error) {
		console.error('加载船舶列表失败:', error)
	}
}

// 加载推荐商品
const loadRecommendProducts = async () => {
	try {
		const response = await productApi.getRecommendProducts({ type: 'ship' })
		recommendProducts.value = response.list || []
	} catch (error) {
		console.error('加载推荐商品失败:', error)
	}
}

// 格式化规格
const formatSpecs = (specs) => {
	if (!specs || typeof specs !== 'object') return ''
	return Object.values(specs).join(' / ')
}

// 选择操作
const toggleSelectAll = () => {
	const newSelected = !isAllSelected.value
	cartItems.value.forEach(item => {
		item.selected = newSelected
	})
}

const toggleItemSelect = (itemId) => {
	const item = cartItems.value.find(item => item.id === itemId)
	if (item) {
		item.selected = !item.selected
	}
}

// 数量操作
const increaseQuantity = async (itemId) => {
	const item = cartItems.value.find(item => item.id === itemId)
	if (item) {
		try {
			await cartApi.updateShipCartItem({
				itemId,
				quantity: item.quantity + 1
			})
			item.quantity++
		} catch (error) {
			console.error('更新数量失败:', error)
		}
	}
}

const decreaseQuantity = async (itemId) => {
	const item = cartItems.value.find(item => item.id === itemId)
	if (item && item.quantity > 1) {
		try {
			await cartApi.updateShipCartItem({
				itemId,
				quantity: item.quantity - 1
			})
			item.quantity--
		} catch (error) {
			console.error('更新数量失败:', error)
		}
	}
}

// 删除商品
const removeItem = (itemId) => {
	uni.showModal({
		title: '确认删除',
		content: '确定要删除这件商品吗？',
		confirmText: '删除',
		cancelText: '取消',
		success: async (res) => {
			if (res.confirm) {
				try {
					await cartApi.removeShipCartItem(itemId)
					const index = cartItems.value.findIndex(item => item.id === itemId)
					if (index > -1) {
						cartItems.value.splice(index, 1)
					}
					uni.showToast({
						title: '已删除',
						icon: 'success'
					})
				} catch (error) {
					console.error('删除失败:', error)
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 船舶操作
const selectShip = (ship) => {
	currentShip.value = ship
	showShipModal.value = false
	
	// 重新加载该船舶的购物车
	loadCartData()
}

const addNewShip = () => {
	showShipModal.value = false
	uni.navigateTo({
		url: '/pages/profile/ship-management?action=add'
	})
}

// 页面跳转
const goToBrowse = () => {
	uni.switchTab({
		url: '/pages/index/index'
	})
}

const goToProductDetail = (productId) => {
	uni.navigateTo({
		url: `/pages/product/detail?id=${productId}`
	})
}

const goToCheckout = () => {
	if (selectedCount.value === 0) {
		uni.showToast({
			title: '请选择要结算的商品',
			icon: 'none'
		})
		return
	}
	
	if (!currentShip.value.id) {
		uni.showToast({
			title: '请先选择船舶',
			icon: 'none'
		})
		return
	}
	
	const selectedItems = cartItems.value.filter(item => item.selected).map(item => ({
		...item,
		specValueId: item.specId || item.specValueId, // 确保包含后端期望的字段名
		productName: item.productName || item.name,
		productImage: item.productImage || item.image,
		selectedSpec: item.specText || item.specs
	}))
	uni.navigateTo({
		url: `/pages/order/confirm?type=ship&shipId=${currentShip.value.id}&items=${JSON.stringify(selectedItems)}`
	})
}
</script>

<style lang="scss" scoped>
.ship-cart-container {
	background: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 100px;
}

.ship-info-bar {
	background: #FFFFFF;
	margin-bottom: 10px;
}

.ship-selector {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px;
	border-bottom: 1px solid #F0F0F0;
}

.ship-details {
	flex: 1;
}

.ship-name {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
	display: block;
	margin-bottom: 4px;
}

.ship-imo {
	font-size: 12px;
	color: #666666;
}

.selector-arrow {
	font-size: 14px;
	color: #CCCCCC;
}

.ship-stats {
	padding: 10px 15px;
	background: #F8F9FA;
}

.stat-item {
	display: flex;
	align-items: center;
	margin-bottom: 4px;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.stat-label {
	font-size: 12px;
	color: #666666;
	margin-right: 8px;
}

.stat-value {
	font-size: 12px;
	color: #333333;
}

.cart-content {
	background: #FFFFFF;
	margin-bottom: 10px;
}

.cart-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px;
	border-bottom: 1px solid #F0F0F0;
}

.select-all {
	display: flex;
	align-items: center;
	gap: 8px;
}

.checkbox {
	font-size: 16px;
	color: #CCCCCC;
	
	&.checked {
		color: var(--primary-color);
	}
}

.select-text {
	font-size: 14px;
	color: #333333;
}

.total-count {
	font-size: 12px;
	color: #666666;
}

.cart-list {
	
}

.cart-item {
	display: flex;
	align-items: center;
	padding: 15px;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
}

.item-checkbox {
	margin-right: 12px;
}

.item-image {
	width: 80px;
	height: 80px;
	border-radius: 8px;
	margin-right: 12px;
}

.item-info {
	flex: 1;
	min-width: 0;
}

.item-name {
	font-size: 14px;
	color: #333333;
	display: block;
	margin-bottom: 6px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.item-specs {
	margin-bottom: 8px;
}

.spec-text {
	font-size: 12px;
	color: #999999;
}

.item-meta {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.item-price {
	font-size: 16px;
	font-weight: 600;
	color: #ff4757;
}

.quantity-controls {
	display: flex;
	align-items: center;
	border: 1px solid #E5E5E5;
	border-radius: 4px;
}

.quantity-btn {
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	color: #333333;
	
	&.minus {
		border-right: 1px solid #E5E5E5;
	}
	
	&.plus {
		border-left: 1px solid #E5E5E5;
	}
}

.quantity-value {
	width: 40px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 14px;
	color: #333333;
}

.item-actions {
	margin-left: 12px;
}

.action-btn {
	color: #999999;
	font-size: 14px;
}

.empty-cart {
	padding: 50px 20px;
	text-align: center;
}

.browse-btn {
	margin-top: 20px;
	width: 120px;
	height: 40px;
	background: var(--primary-color);
	color: #FFFFFF;
	border: none;
	border-radius: 20px;
}

.browse-text {
	color: #FFFFFF;
}

.recommend-section {
	background: #FFFFFF;
	margin-bottom: 10px;
}

.section-header {
	padding: 15px;
	border-bottom: 1px solid #F0F0F0;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
}

.recommend-list {
	padding: 15px;
	white-space: nowrap;
}

.recommend-item {
	display: inline-block;
	width: 120px;
	margin-right: 12px;
	vertical-align: top;
}

.recommend-image {
	width: 120px;
	height: 120px;
	border-radius: 8px;
	margin-bottom: 8px;
}

.recommend-name {
	font-size: 12px;
	color: #333333;
	display: block;
	margin-bottom: 4px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.recommend-price {
	font-size: 14px;
	font-weight: 600;
	color: #ff4757;
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #FFFFFF;
	padding: 15px;
	border-top: 1px solid #E5E5E5;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.bar-left {
	flex: 1;
}

.total-info {
	margin-bottom: 4px;
}

.total-label {
	font-size: 14px;
	color: #333333;
}

.total-price {
	font-size: 18px;
	font-weight: 600;
	color: #ff4757;
	margin-left: 4px;
}

.save-info {
	font-size: 12px;
	color: #52c41a;
}

.checkout-btn {
	width: 120px;
	height: 44px;
	background: var(--primary-color);
	color: #FFFFFF;
	border: none;
	border-radius: 8px;
	
	&.disabled {
		background: #CCCCCC;
	}
}

.checkout-text {
	color: #FFFFFF;
}

.ship-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: center;
}

.ship-modal-content {
	background: #FFFFFF;
	border-radius: 12px;
	margin: 0 20px;
	width: calc(100% - 40px);
	max-height: 70vh;
	overflow: hidden;
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #F0F0F0;
}

.modal-title {
	font-size: 18px;
	font-weight: 600;
	color: #333333;
}

.modal-close {
	font-size: 18px;
	color: #999999;
}

.ship-list {
	max-height: 300px;
	overflow-y: auto;
}

.ship-option {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&.active {
		background: #F0F8FF;
	}
}

.ship-info {
	flex: 1;
}

.ship-name {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
	display: block;
	margin-bottom: 4px;
}

.ship-imo,
.ship-port {
	font-size: 12px;
	color: #666666;
	display: block;
	margin-bottom: 2px;
}

.ship-check {
	font-size: 16px;
	color: var(--primary-color);
}

.modal-footer {
	padding: 20px;
	border-top: 1px solid #F0F0F0;
}

.add-ship-btn {
	width: 100%;
	height: 44px;
	background: #F8F9FA;
	border: 1px dashed #CCCCCC;
	border-radius: 8px;
}

.add-ship-text {
	color: #666666;
}
</style>